package org.imlinker.message;

import java.util.ArrayList;

import org.imlinker.list.ListItem;
import org.imlinker.list.ListModel;
import org.imlinker.login.Core;

@SuppressWarnings("serial")
public class MessageList extends ListModel {

	private BlackList blackList;

	public MessageList(Core core) {
		this.core = core;

		blackList = new BlackList();
	}

	public void addMessage(final MessageItem item) {
		if (blackList.isBlack(item.getName())) {
			return;
		}

		int size = this.size();
		MessageItem iter;
		for (int i = 0; i < size; i++) {
			iter = (MessageItem) this.getElementAt(i);
			if (iter.getName().endsWith(item.getName())) {
				return;
			}
		}

		addElement(item);
		core.setMessageNum(this.size());
	}

	public void deleteMessage(final MessageItem item) {
		if (this.contains(item)) {
			this.removeElement(item);
		}

		core.setMessageNum(this.size());
	}

	public boolean openFirstMessage() {
		MessageItem item = (MessageItem) getElementAt(0);
		item.open();

		this.deleteMessage(item);

		return true;
	}

	@Override
	public void openItem(final ListItem object) {
		if (object instanceof MessageItem) {
			MessageItem message = (MessageItem) object;
			message.open();

			this.deleteMessage(message);
		}
	}

	public void setBlackName(String blackName) {
		blackList.addElement(blackName);

		ArrayList<MessageItem> toRemoveList = new ArrayList<MessageItem>();
		for (int i = 0; i < this.size(); i++) {
			if (blackList.isBlack(((MessageItem) this.get(i)).getName())) {
				toRemoveList.add((MessageItem) this.get(i));
			}
		}

		for (int i = 0; i < toRemoveList.size(); i++) {
			this.deleteMessage(toRemoveList.get(i));
		}
	}

	public void removeBlackName(String name) {
		blackList.removeElement(name);
	}

	private Core core;

}
